package org.example.chatroom.common.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LIUYANJIAO
 * Date: 2025-06-21
 * Time: 17:55
 */
@Slf4j
public class SecurityUtil {
    /**
     * 加密
     * @param password 密码加密
     * @return
     */
    public static String encrypt(String password){
        String salt = UUID.randomUUID().toString().replace("-","");
        String finalPassword = DigestUtils.md5DigestAsHex((salt+password).getBytes(StandardCharsets.UTF_8));
        return salt+finalPassword;
    }
    public static boolean verify(String password,String finalpassword){
        if(!StringUtils.hasLength(password)
        ||!StringUtils.hasLength(finalpassword)){
            return false;
        }
        if(finalpassword.length()!=64){
            return false;
        }
        String salt = finalpassword.substring(0,32);
        String securityPassword = DigestUtils.md5DigestAsHex((salt+password).getBytes(StandardCharsets.UTF_8));
        log.info("password: {}",securityPassword);
        log.info("finalpassword: {}",finalpassword);
        return finalpassword.equals(salt+securityPassword);
    }
}
